package org.projectback.entity.AccountEntity;

import lombok.Data;
import org.springframework.security.core.GrantedAuthority;

import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Data
public class CustomUser implements UserDetails {
    private Long id;
    private String username;
    private String password;
    private Collection<? extends GrantedAuthority> authorities;
    private String email;
    private String phone;
    private String role;


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    public void setAuthorities() {
        List<GrantedAuthority> authorities = new ArrayList<>(role.length());

        for(String role : role.split(",")) {
            Assert.isTrue(!role.startsWith("ROLE_"), () -> role + " cannot start with ROLE_ (it is automatically added)");
            authorities.add(new SimpleGrantedAuthority("ROLE_" + role));
        }
        this.authorities = authorities;
    }

    public void setRole(String role) {
        this.role = role;
        setAuthorities();
    }

    @Override
    public boolean equals(Object obj) {
        //会话并发生效，使用username判断是否是同一个用户

        if (obj instanceof CustomUser) {
            //字符串的equals方法是已经重写过的
            return ((CustomUser) obj).getUsername().equals(this.username);
        } else {
            return false;
        }

    }
}
